package logic

import (
	"context"
	"time"
	"xialou_platform/services/wallet/model"

	"xialou_platform/services/wallet/rpc/internal/svc"
	"xialou_platform/services/wallet/rpc/walletClient"

	"github.com/zeromicro/go-zero/core/logx"
)

type WalletBindBankCardLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWalletBindBankCardLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WalletBindBankCardLogic {
	return &WalletBindBankCardLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 钱包绑定银行卡
func (l *WalletBindBankCardLogic) WalletBindBankCard(in *walletClient.WalletBindBankCardReq) (*walletClient.EmptyBody, error) {
	wallet, err := l.svcCtx.WalletModel.FindOneBySourceId(l.ctx, in.SourceId)
	if err != nil && err != model.ErrNotFound {
		return nil, err
	}
	nowTime := time.Now()
	if wallet == nil {
		_, err := l.svcCtx.WalletModel.Insert(l.ctx, &model.Wallet{
			Id:          l.svcCtx.Flake.Generate().Int64(),
			SourceType:  1,
			SourceId:    in.SourceId,
			Balance:     0,
			Status:      1,
			BankNumber:  in.BankNumber,
			BankName:    in.BankName,
			CreateTime:  nowTime,
			UpdateTime:  nowTime,
			AccountName: in.AccountName,
		})
		if err != nil {
			return nil, err
		}
	} else {
		wallet.BankNumber = in.BankNumber
		wallet.BankName = in.BankName
		wallet.UpdateTime = nowTime
		wallet.AccountName = in.AccountName
		err := l.svcCtx.WalletModel.Update(l.ctx, wallet)
		if err != nil {
			return nil, err
		}
	}

	return &walletClient.EmptyBody{}, nil
}
